<template>
  <Container>
    <template slot="top">
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="上传人" prop="createUserId">
          <el-select
              v-model="queryParams.createUserId"
              placeholder="请选择上传人"
              clearable
              filterable
          >
            <el-option
                v-for="user in userSelectData"
                :key="user.value"
                :label="user.label"
                :value="user.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="文件名" prop="fileName">
          <el-input
            v-model="queryParams.fileName"
            placeholder="请输入文件名"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="源文件名" prop="originalName">
          <el-input
            v-model="queryParams.originalName"
            placeholder="请输入源文件名"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="开始日期">
          <el-date-picker
              v-model="queryParams.startTime"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束日期">
          <el-date-picker
              v-model="queryParams.endTime"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="文件类型" prop="fileType">
          <el-input
              v-model="queryParams.fileType"
              placeholder="请输入文件类型"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleFile"
            v-hasPermi="['system:file:upload']"
          >上传文件</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleImage"
            v-hasPermi="['system:file:upload']"
          >上传图片</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
              type="primary"
              plain
              icon="el-icon-refresh"
              size="mini"
              :loading="loadingClear"
              @click="handleClear"
              v-hasPermi="['system:file:remove']"
          >清理无用文件</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:file:remove']"
          >删除</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
    </template>
    <template slot="center">
      <el-table v-loading="loading" :data="fileList" @selection-change="handleSelectionChange"
                :header-cell-class-name="handleHeaderClass"
                @header-click="handleHeaderCLick"
                :border="true"
                height="100%"
                v-if="showTable">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="主键" align="center" prop="fileId" v-if="false"/>
        <el-table-column label="文件名" align="center" prop="fileName" />
        <el-table-column label="源文件名" align="center" prop="originalName" />
        <el-table-column label="文件展示" align="center" prop="fileUrl">
          <template slot-scope="scope">
            <ImagePreview
                v-if="isImageSuffix(scope.row.fileType)"
                :width=100
                :height=100
                :src="scope.row.fileUrl"
                :preview-src-list="[scope.row.fileUrl]"/>
            <span v-text="scope.row.originalName" v-if="!isImageSuffix(scope.row.fileType)"/>
          </template>
        </el-table-column>
        <el-table-column label="访问路径" width="200" align="center" prop="fileUrl" />
        <el-table-column label="存储路径" width="200" align="center" prop="filePath" />
        <el-table-column label="文件类型" width="80" align="center" prop="fileType" />
        <el-table-column label="文件大小" width="100" align="center" prop="fileSize" />
        <el-table-column label="上传时间" align="center" prop="createTime" sortable="custom">
          <template slot-scope="scope">
            <span>{{ $parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="上传人" align="center" prop="createUserId">
          <template slot-scope="scope">
            <template v-for="(item, index) in userSelectData">
              <span v-if="item.value == scope.row.createUserId">{{ item.label }}</span>
            </template>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" />
        <el-table-column label="关联业务表" align="center" prop="tableName" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleDownload(scope.row)"
              v-hasPermi="['system:file:download']"
            >下载</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['system:file:remove']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>
    <template slot="bottom">
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </template>
    <!-- 添加文件对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="文件名">
          <FileUpload v-model="form.file" v-if="type === 0"/>
          <ImageUpload v-model="form.file" v-if="type === 1"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </Container>
</template>

<script>
import { pageFile, delFile,clearFile } from "@/api/system/file";
import { userAllSelect} from '@/api/system/user'
export default {
  name: "File",
  data() {
    return {
      showTable: true,
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 文件数据
      fileList: [],
      // 弹出层标题
      title: "",
      // 弹出层标题
      type: 0,
      // 是否显示弹出层
      open: false,
      // 默认排序
      defaultSort: {prop: 'createTime', order: 'ascending'},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        fileName: undefined,
        originalName: undefined,
        startTime: undefined,
        endTime: undefined,
        fileType: undefined,
        createUserId: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        file: [
          { required: true, message: "文件不能为空", trigger: "blur" }
        ]
      },
      userSelectData:[],
      loadingClear:false
    };
  },
  created() {
    this.getUserAllSelect();
    this.getList();
  },
  methods: {
    /**
     * 查询用户下拉数据
     */
    getUserAllSelect(){
      userAllSelect().then(response => {
        this.userSelectData=response.data;
      });
    },
    /**
     * 查询文件列表
     */
    getList() {
      this.loading = true;
      pageFile(this.queryParams).then(response => {
        this.fileList = response.rows;
        this.total = response.total;
        this.loading = false;
        this.showTable = true;
      });
    },
    /**
     * 是否是图片类型后缀
     * @param fileType
     * @returns {boolean}
     */
    isImageSuffix(fileType) {
      let arr = ["png", "jpg", "jpeg"];
      return arr.some(type => {
        return fileType.indexOf(type) > -1;
      });
    },
    /**
     * 表单重置
     */
    reset() {
      this.form = {
        file: undefined,
      };
      this.$resetForm("form");
    },
    /**
     * 搜索
     */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /**
     * 重置
     */
    resetQuery() {
      this.showTable = false;
      this.$resetForm("queryForm");
      this.queryParams.orderByColumn = this.defaultSort.prop;
      this.queryParams.isAsc = this.defaultSort.order;
      this.handleQuery();
    },
    /**
     * 多选框选中数据
     * @param selection
     */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.fileId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /**
     * 设置列的排序为我们自定义的排序
     * @param column
     */
    handleHeaderClass({column}) {
      column.order = column.multiOrder
    },
    /**
     * 点击表头进行排序
     * @param column
     */
    handleHeaderCLick(column) {
      if (column.sortable !== 'custom') {
        return
      }
      switch (column.multiOrder) {
        case 'descending':
          column.multiOrder = 'ascending';
          break;
        case 'ascending':
          column.multiOrder = '';
          break;
        default:
          column.multiOrder = 'descending';
          break;
      }
      this.handleOrderChange(column.property, column.multiOrder)
    },
    /**
     * 处理排序
     * @param prop
     * @param order
     */
    handleOrderChange(prop, order) {
      let orderByArr = this.queryParams.orderByColumn ? this.queryParams.orderByColumn.split(",") : [];
      let isAscArr = this.queryParams.isAsc ? this.queryParams.isAsc.split(",") : [];
      let propIndex = orderByArr.indexOf(prop)
      if (propIndex !== -1) {
        if (order) {
          //排序里已存在 只修改排序
          isAscArr[propIndex] = order;
        } else {
          //如果order为null 则删除排序字段和属性
          isAscArr.splice(propIndex, 1);//删除排序
          orderByArr.splice(propIndex, 1);//删除属性
        }
      } else {
        //排序里不存在则新增排序
        orderByArr.push(prop);
        isAscArr.push(order);
      }
      //合并排序
      this.queryParams.orderByColumn = orderByArr.join(",");
      this.queryParams.isAsc = isAscArr.join(",");
      this.getList();
    },
    /**
     * 上传文件
     */
    handleFile() {
      this.reset();
      this.open = true;
      this.title = "上传文件";
      this.type = 0;
    },
    /**
     * 上传图片
     */
    handleImage() {
      this.reset();
      this.open = true;
      this.title = "上传图片";
      this.type = 1;
    },
    /**
     * 清理文件
     */
    handleClear(){
      this.loadingClear=true
      clearFile().then(response => {
        this.$modal.msgSuccess(response.data);
      }).finally(()=>{
        this.loadingClear=false
      });
    },
    /**
     * 提交按钮
     */
    submitForm() {
      this.open = false;
      this.getList();
    },
    /**
     * 下载
     * @param row
     */
    handleDownload(row) {
      this.$download.file(row.fileId)
    },
    /**
     * 删除
     * @param row
     */
    handleDelete(row) {
      let fileIds = row.fileId;
      if(row.fileId){
        fileIds = row.fileId;
      }else{
        fileIds = this.ids.join(",")
      }
      this.$modal.confirm('是否确认删除编号为"' + fileIds + '"的数据项?').then(() => {
        this.loading = true;
        return delFile(fileIds);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).finally(() => {
        this.loading = false;
      });
    },
  }
};
</script>
